<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-select v-model="queryParams.year" placeholder="选择年份" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="选择季度" class="ml-10 mr-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.deptId" placeholder="选择待审批站办所" class="ml-10" no-data-text="暂无待审批站办所" @change="getList">
          <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="text-banner">
      <span>干部工作情况汇总（共 {{ workTotal }} 条）</span>
      <el-button size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
    </div>
    <div v-loading="workLoading">
      <!-- <div class="float-right mb-10">
        <el-button
          size="mini"
          type="primary"
          plain
          icon="el-icon-menu"
          :disabled="!selectionList.length"
          v-hasPermi="['approval:cadre-supervision:pass']"
          @click="handleBatchApproval('pass')"
        >
          批量通过
        </el-button>
        <el-button
          size="mini"
          type="danger"
          plain
          icon="el-icon-menu"
          :disabled="!selectionList.length"
          v-hasPermi="['approval:cadre-supervision:reject']"
          @click="handleBatchApproval('reject')"
        >
          批量退回
        </el-button>
      </div> -->

      <el-table :data="workList" border style="width: 100%">
        <!-- <el-table-column type="selection" width="55" :selectable="checkSelectable"> </el-table-column> -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <!-- <div style="padding: 10px 20px">
                  <el-card> -->
            <el-table :data="props.row.personalWorkPlanScoreList" border stripe style="width: 100%">
              <el-table-column prop="civilServantName" label="参与人" align="center"></el-table-column>
              <el-table-column prop="workCompletionStageDict" width="150" label="完成状态" align="center">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.biz_work_completion_stage" :value="scope.row.workCompletionStageDict" />
                </template>
              </el-table-column>
              <el-table-column prop="workCompletionSituation" label="完成情况" min-width="180" align="center">
                <template slot-scope="scope">
                  <span class="pre-wrap align-left">{{ scope.row.workCompletionSituation || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="workCompletionMaterialUrls" label="完成材料" min-width="180" align="center">
                <template slot-scope="scope">
                  <div v-if="scope.row.workCompletionMaterialUrls">
                    <el-tooltip
                      v-for="(url, index) in scope.row.workCompletionMaterialUrls.split(',')"
                      :key="index"
                      effect="dark"
                      :content="formatFileUrl(url)['name']"
                      placement="top-start"
                    >
                      <el-button type="text" @click="handlePreviewFile(url)" class="file-preview-btn">
                        {{ formatFileUrl(url)['name'] }}
                      </el-button>
                    </el-tooltip>
                  </div>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="workCompletionDate" label="完成日期" width="160" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.workCompletionDate || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="firstSupervisionScore" label="核查得分" width="130" align="center"> </el-table-column>
              <el-table-column prop="firstSupervisionSituation" label="核查情况" width="150" align="center"></el-table-column>
            </el-table>
            <!-- </el-card>
                </div> -->
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="workType" label="工作类型" align="center" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.biz_work_type" :value="scope.row.workType" />
          </template>
        </el-table-column>
        <el-table-column prop="civilServantName" label="参与人" align="center"></el-table-column>
        <el-table-column prop="workContent" label="工作内容" min-width="180" align="center"> </el-table-column>
        <el-table-column prop="planScore" label="分值" width="80" align="center"> </el-table-column>
        <el-table-column label="操作" align="center" width="140">
          <template slot-scope="scope">
            <ApprovalLog :biz-id="scope.row.workScoreLogId" v-show="checkBtnVisible('finish', scope.row.workSupervisionAuditStatusDict)">
              <el-button type="text" size="mini" class="color-success" icon="el-icon-check">[审核通过]</el-button>
            </ApprovalLog>
            <ApprovalLog :biz-id="scope.row.workScoreLogId" v-show="checkBtnVisible('returned', scope.row.workSupervisionAuditStatusDict)">
              <el-button type="text" size="mini" class="color-error" icon="el-icon-check">[已退回]</el-button>
            </ApprovalLog>
            <ApprovalLog
              :biz-id="scope.row.workScoreLogId"
              v-show="checkBtnVisible('pass', scope.row.workSupervisionAuditStatusDict)"
              v-hasPermi="['approval:cadre-supervision:pass']"
            >
              <el-button type="text" size="mini" @click.stop="handleApproval(scope.$index, scope.row, 'pass')"> 通过 </el-button>
            </ApprovalLog>
            <ApprovalLog
              :biz-id="scope.row.workScoreLogId"
              v-show="checkBtnVisible('reject', scope.row.workSupervisionAuditStatusDict)"
              v-hasPermi="['approval:cadre-supervision:reject']"
            >
              <el-button type="text" size="mini" @click.stop="handleApproval(scope.$index, scope.row, 'reject')" class="color-danger ml-10">
                退回
              </el-button>
            </ApprovalLog>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <FilePreview :visible.sync="filePreviewVisible" :file="previewFile"></FilePreview>
  </div>
</template>

<script>
import { list as listPlan, approval, listDept } from '@/api/work-approval/cadre-supervision'
import { quarterFormat } from '@/utils/quarter.js'
import FilePreview from '@/components/FilePreview'
import { mixins } from '@/mixins'
import ApprovalLog from '@/components/ApprovalLog'

export default {
  name: 'cadre-supervision-approval',
  mixins: [mixins],
  dicts: ['biz_work_year_list', 'biz_work_type', 'biz_work_score_type', 'biz_work_completion_stage', 'biz_dept_important_work_completion'],
  props: {},
  components: { FilePreview, ApprovalLog },
  data() {
    return {
      previewFile: {},
      filePreviewVisible: false,
      workTotal: 0,
      workList: [],
      workLoading: false,
      quarterOptions: [],
      queryParams: {
        year: '',
        quarter: '',
        workSupervisionAuditStatusDict: 'DSH',
        deptId: undefined
      },
      selectionList: [],
      deptOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleYearChange(new Date().getFullYear())
  },
  methods: {
    // 表格多选
    handleSelectionChange(selection) {
      this.selectionList = selection
    },
    // 获取部门
    async getDeptList() {
      let params = JSON.parse(JSON.stringify(this.queryParams))
      delete params.deptId
      delete params.workSupervisionAuditStatusDict
      listDept(params).then(res => {
        let { data } = res
        if (Array.isArray(data) && data.length) {
          this.deptOptions = res.data.map(item => {
            return { label: item.deptName, value: item.deptId }
          })
          let findDept = this.deptOptions.find(item => item.value === this.queryParams.deptId)
          if (!findDept) {
            this.queryParams.deptId = this.deptOptions[0].value
          }
        } else {
          this.deptOptions = []
          this.queryParams.deptId = ''
        }
        this.getList()
      })
    },
    handleRefresh() {
      this.getDeptList()
    },
    // 校验表格是否可选
    checkSelectable(raw, index) {
      if (raw.supervisionAuditStatusDict === 'DSH') {
        return true
      }
      return false
    },

    // 批量审批
    handleBatchApproval(operation) {
      let auditRemark = '同意'
      let auditStatusDict = 'SHTG'
      if (operation === 'reject') {
        auditRemark = '不同意'
        auditStatusDict = 'SHBTG'
      }
      let params = this.selectionList.map(item => {
        return { id: item.id, auditRemark, auditStatusDict }
      })
      let content = `您正在审批已选中的 ${this.selectionList.length} 项工作，请输入审批意见`
      this.approvalPrompt(operation, content, auditRemark, params)
    },

    // 审批操作
    handleApproval(index, raw, operation) {
      let params = { id: raw.id, auditStatusDict: 'SHTG', auditRemark: '同意' }
      if (operation === 'reject') {
        params.auditStatusDict = 'SHBTG'
        params.auditRemark = '不同意'
      }
      let content = `您正在审批第 【${index + 1}】 项工作，请输入审批意见`
      this.approvalPrompt(operation, content, params.auditRemark, [params])
    },
    // 审批窗口
    approvalPrompt(operation, content, inputValue, params) {
      this.$prompt(content, '审批提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '输入审批意见',
        inputType: 'textarea',
        inputPattern: /\S/,
        inputValue: inputValue,
        inputErrorMessage: '审批意见不能为空',
        beforeClose: (action, instance, done) => {
          params.forEach(item => {
            item.auditRemark = instance.inputValue
          })
          if (action === 'confirm') {
            const loading = this.$loading({
              target: '.el-message-box',
              lock: true,
              text: '数据处理中',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.6)'
            })
            approval(params)
              .then(() => {
                loading.close()
                if (operation === 'pass') {
                  this.$modal.msgSuccess('已通过')
                } else if (operation === 'reject') {
                  this.$modal.msgError('已退回')
                }
                this.handleRefresh()
                done()
              })
              .catch(() => {
                loading.close()
                done()
              })
          } else {
            done()
          }
        }
      })
    },
    // 功能类型、审核状态、提交状态
    checkBtnVisible(type, audit) {
      switch (type) {
        case 'pass': // 通过
        case 'reject': // 退回
          return audit === 'DSH'
        case 'finish': // 审核已完成
          return audit === 'SHTG'
        case 'returned': // 审核已完成
          return audit === 'SHBTG'
        default:
          return false
      }
    },
    // 校验工作计划表单字段是否可填
    checkWorkPlanDisabled(audit) {
      if (audit === 'SHTG' || audit === 'DSH') {
        return true
      }
      return false
    },
    // 预览文件
    handlePreviewFile(url) {
      let fileItem = this.formatFileUrl(url)
      this.previewFile = { url, ...fileItem }
      this.filePreviewVisible = true
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      this.handleRefresh()
    },
    // 表格数据处理
    tableFormat(list) {
      for (let item of list) {
        item.civilServantName = item.personalWorkPlanScoreList
          .map(civil => {
            return civil.civilServantName
          })
          .join('、')
        item.personalWorkPlanScoreList.forEach(element => {
          element.workReportMark = item.workReportMark
        })
      }
      this.workList = list
    },
    getList() {
      this.workLoading = true
      listPlan(this.queryParams)
        .then(res => {
          this.workLoading = false
          let { rows } = res
          this.workTotal = rows.length || 0
          this.tableFormat(rows)
        })
        .catch(err => (this.workLoading = false))
    }
  }
}
</script>

<style lang="scss" scoped>
.file-preview-btn {
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  margin-left: 0;
  padding: 0;
}

::v-deep .el-input-number--medium {
  width: auto;
}
::v-deep .el-table__expanded-cell {
  background-color: #fafafa;
  padding: 15px;
}
</style>
